package com.xiangxiao.rpan.authority.oauth;

import com.xiangxiao.rpan.utils.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2024/10/16 17:42
 */
@Slf4j
public class TokenCodec {
  /**
   * 生成token
   *
   * @param tenancyId
   * @param login
   * @param channel
   * @return
   */
  public String createToken(long tenancyId, String login, String channel) {
    try {
      String content = login + "_" + tenancyId + "_" + channel;
      String salt = RandomStringUtils.randomAlphabetic(6);
      return salt + "_" + AesUtil.encodeAES(salt, content);
    } catch (Exception e) {
      return null;
    }
  }

  /**
   * 解析token
   *
   * @param token
   * @return
   */
  public String[] extractorToken(String token) {
    if (StringUtils.isBlank(token)) {
      return null;
    }

    int index = token.indexOf("_");
    if (index < 0) {
      return null;
    }

    String encodeToken = token.substring(index + 1);
    String salt = token.substring(0, index);
    try {
      String userInfo = AesUtil.decodeAES(salt, encodeToken);
      return userInfo.split("_");
    } catch (Exception e) {
      log.error("token解析异常,token={}", e);
      return null;
    }
  }
}
